#!/bin/bash
set -e

# 获取脚本所在目录
SCRIPT_FOLDER=$(dirname $(readlink -f "$0"))

#设置flutter sdk路径和待测试应用路径
FLUTTER_SDK_DIR="$SCRIPT_FOLDER/flutter_flutter"
CAMERA_DEMO_DIR="$SCRIPT_FOLDER/flutter_packages/packages/camera/camera_ohos/example"
if [ ! -d "$FLUTTER_SDK_DIR" ] || [ ! -d "$CAMERA_DEMO_DIR" ]; then
    echo "Flutter SDK目录或待测试应用目录不存在，请检查路径是否正确！"
    exit 1
fi

# 提示用户输入PR编号
read -p "请输入PR编号，用空格分隔多个PR编号（例如：1234 5678）: " PR_NUMBERS
if [[ -z "$PR_NUMBERS" ]]; then
    echo "没有输入PR编号，脚本将退出。"
    exit 1
fi
# TODO: 检查pr编号中没有重复的

# 切换到项目目录
echo "正在切换到项目目录: $FLUTTER_SDK_DIR"
cd "$FLUTTER_SDK_DIR"

# 删除bin/cache目录
echo "正在删除bin/cache目录..."
rm -rf "$FLUTTER_SDK_DIR/bin/cache"

git checkout master

# 遍历所有PR编号
for PR in $PR_NUMBERS; do
    PR_NUMBER=$PR
    BRANCH_NAME="pr_$PR_NUMBER"

    cd "$FLUTTER_SDK_DIR"
    # 如果此pr已存在同名分支，则删除
    git branch -D $BRANCH_NAME 2>/dev/null || true

    # 检出PR对应的分支
    echo "正在检出PR编号为 $PR_NUMBER 的分支..."
    git fetch origin
    git fetch https://gitcode.com/openharmony-tpc/flutter_flutter.git  +refs/merge-requests/$PR_NUMBER/head:$BRANCH_NAME
    git checkout $BRANCH_NAME

    if [[ $? -ne 0 ]]; then
        echo "检出PR分支失败，请检查PR编号是否正确！"
        exit 1
    fi

    echo "PR分支检出成功！"

    # 切换到camera包的demo目录
    echo "正在切换到camera包的demo目录: $CAMERA_DEMO_DIR"
    cd "$CAMERA_DEMO_DIR"

    # 清理camera包的demo
    echo "正在清理camera包的demo..."
    "$FLUTTER_SDK_DIR/bin/flutter" clean

    if [[ $? -ne 0 ]]; then
        echo "清理camera包的demo失败！"
        exit 1
    fi

    # 获取camera包的demo依赖
    echo "正在获取camera包的demo依赖..."
    "$FLUTTER_SDK_DIR/bin/flutter" pub get

    if [[ $? -ne 0 ]]; then
        echo "获取camera包的demo依赖失败！"
        exit 1
    fi

    # 获取camera包的demo依赖
    echo "更新flutter依赖版本..."
    "$FLUTTER_SDK_DIR/bin/flutter" pub upgrade

    # 编译camera demo
    echo "正在编译camera demo..."
    "$FLUTTER_SDK_DIR/bin/flutter" build hap --release

    if [[ $? -ne 0 ]]; then
        echo "编译camera包的demo失败！"
        exit 1
    fi

    echo "camera包的demo编译成功！"
    echo "------------------------------"
    echo "PR $PR_NUMBER 处理完成"
    echo "------------------------------"
done

echo "所有PR测试完成！"